package com.fept.msgcore.scheduler.job.base;

import com.fept.msgcore.scheduler.job.manager.ScheduleManager;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by Srma on 2/10/2017.
 */
public abstract class BaseScheduleJob implements Job{
    protected static Logger logger = LoggerFactory.getLogger(BaseScheduleJob.class);

    public BaseScheduleJob() {
    }

    public abstract String getTimeExpression();

    public String getJobName() {
        return this.getClass().getSimpleName();
    }

    protected boolean validate() {
        return true;
    }

    protected void before() {
    }

    protected void after() {
    }

    public abstract void process() throws SchedulerException;

    protected void jobProfile(long jobStartTime, long jobEndTime) {
    }

    protected void jobProcessProfile(long jobProcessStartTime, long jobProcessEndTime) {
    }

    protected void doExecute(JobExecutionContext context) throws JobExecutionException {
        long jobStartTime = (new Date()).getTime();

        long jobEndTime;
        try {
            if(this.validate()) {
                this.before();
                jobEndTime = (new Date()).getTime();
                this.process();
                long e = (new Date()).getTime();
                this.after();
                this.jobProcessProfile(jobEndTime, e);
            }
        } catch (Exception var9) {
            logger.error("exception on doExecute");
            logger.error(var9.getMessage());
        }

        jobEndTime = (new Date()).getTime();

        try {
            this.jobProfile(jobStartTime, jobEndTime);
        } catch (Exception var8) {
            logger.error("exception on jobProfiling");
            logger.error(var8.getMessage());
        }

    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        this.doExecute(context);
    }

    protected synchronized void register() {
        try {
            ScheduleManager.getInstance().register(this);
        } catch (Exception var2) {
            logger.error("exception on job registering");
            logger.error(var2.getMessage());
        }

    }
}
